<?php

/**
 * 权限与组操作
 *
 */
class PowerGroup {

    protected $main_table = 'sys_power';
    protected $main_table2 = 'sys_group';
    protected $db = null;

    public function __construct($db) {
        $this->db = $db;
    }

    public function __destruct() {
        unset($this->db);
    }

    /**
     * 	insert power
     * 	@param array $data
     * 	@return int affected count
     */
    public function insert_power($data) {
        if (!is_array($data))
            my_jump('输入的参数有误');
        $rows = $this->db->insert($this->main_table, $data);
		$insert_id = $this->db->getInsertId();
        return $insert_id;
    }

    /**
     * 	update power
     * 	@param array $data
     * 	@param array or string $where
     * 	@return int affected count
     */
    public function update_power($data, $where) {
        if (!is_array($data))
            my_jump('输入的参数有误');
        $result = $this->db->update($this->main_table, $data, $where);
        return $result;
    }

    /**
     * 	delete power
     * 	@param array or string $where
     * 	@return int affected count
     */
    public function del_power($where) {
        $result = $this->db->delete($this->main_table, $where);
        return $result;
    }

    /**
     * 	rebuild power
     *  @param string $where
     *	@param array $data
     * 	@param int $type
     * 	@return int affected count
     */
    public function rebuild_power($where, $data, $type=1,$action_file) {
        if ($type && is_file($action_file)) {
            if (!is_array($data) || !$where)
                my_jump('输入的参数有误');
            $result = $this->check_exist($where);
            if (!$result)
                $result = $this->insert_power($data);
            return $result;
        }
    }

    /**
     * 	check power exist
     * 	@param string $where
     * 	@return int check_id
     */
    public function check_exist($where) {
        $sql = "SELECT power_id FROM " . $this->main_table . " WHERE " . $where;
        $result = $this->db->getOne($sql);
        return $result;
    }

    /**
     * 	get power info
     * 	@param int $id
     * 	@param array $field or string '*'
     * 	@return array one row data
     */
    public function get_power_row($id, $field='*') {
		
        $sql = "SELECT " . $field . " FROM " . $this->main_table . " WHERE power_id ='" . intval($id) . "' ";
	
        $data = $this->db->getRow($sql);
        return $data;
    }

    /**
     * 	insert group
     * 	@param array $data
     * 	@return int affected count

      public function insert_group($data){
      if(!is_array($data))
      my_jump('输入的参数有误');
      $rows = $this->db->insert($this->main_table2, $data);
      $insert_id = $this->db->getInsertId();
      return $insert_id;
      }
     */
	 
    public function insert_group($data, $pid,$setid='') {
        if (!is_array($data))
            my_jump('输入的参数有误');
		//$this->db->begin();
        if ($pid) {
            $row = $this->get_group_row($pid);
			
            if ($row) {
				if(!$setid){
					$setid = $this->db->getOne("SELECT max(g_id) FROM ".$this->main_table2)+1;
				}
				$check = $this->db->getOne("SELECT g_id FROM ".$this->main_table2." where g_id='".$setid."'" );
				if($check){
					my_jump('指定的ID已被使用');	
				}
				$nav = $row['g_nav'].$setid.',';
				$view_power = $row['g_view_power'];
				
              	$data['g_id'] = $setid;
				$data['g_nav'] = $nav;
				$data['g_view_power'] = $view_power;
				$data['g_level'] = $row['g_level']+1;
				$data['g_root'] =($data['g_level']=='1') ? $setid : $row['g_root'];
				
				switch($data['g_type']){
					case "1":									//樹型向下
					break;
					case "2":									//指定範圍
					break;
					case "3":									//全部
					break;	
					default:									//本人
					break;
					
				}

			} else {
                my_jump('没有此分类信息');
            }
        } else {
			if(!$setid){
					$setid = $this->db->getOne("SELECT max(g_id) FROM ".$this->main_table2)+1;
			}
			$data['g_id'] = $setid;
			$data['g_nav'] = ','.$setid.',';
			$data['g_level'] = '0';
			$data['g_root'] = '0';
        }
      
       	$rs = $this->db->insert($this->main_table2, $data);
		
		if($rs){
			return $rs;
		}else{
			return false;
		}
		
        //$insert_id = $this->db->getInsertId();
        //return $insert_id;
		//return $rows;
    }
/*
	public function my_update($data,$id,$pid){
		if ($pid){
			$row = $this->get_group_row($pid);
			$data['g_root'] = $row['g_level'] ? $row['g_root'] : $id;
			$data['g_more_power'] = $id.',';
			$data['g_level'] = $row['g_level']+1;
		}else{
			$data['g_id'] = '0';
			$data['g_root'] = $id;
			$data['g_more_power'] = ','.$id.',';
			$data['g_level'] = '0';
		
		}
		$this->db->setDebug(1,1);
		$rs = $this->db->update($this->main_table2, $data, "g_id='$id'");
		return $rs;
	}

*/
	public function insert_data($data, $pid,$setid=''){
		if(!is_array($data))
		my_jump('输入的参数有误');
		if(intval($setid)>0){
			//$this->db->setDebug(1,1);
			$max = $this->db->getOne("SELECT g_id FROM ".$this->main_table2." WHERE g_id='".$setid."'");
			if($max)
			my_jump('此id已存在数据');
                        $max = $setid;
		}else{
			$max = $this->db->getOne("SELECT MAX(g_id) as max FROM ".$this->main_table2)+1 ;
		}
		
		//子栏目
		if($pid > 0){			
			$row = $this->get_group_row($pid);
			$data['g_id'] = $max;
			$data['g_root'] = $row['g_root'];
			$data['g_more_power'] = $row['g_more_power'].$max.',';
			$data['g_level'] = $row['g_level']+1;
			$data['g_view_power'] = $row['g_view_power'];
		}else{	
			$data['g_id'] = $max;
			$data['g_root'] = '1';
			$pid = 0;
			$data['g_more_power'] = $max.',';
			$data['g_level'] = $max;
		}
         //      $this->db->setDebug(1,1);
		$rows = $this->db->insert($this->main_table2, $data);
		//$insert_id = $this->db->getInsertId();

		/*
		if($insert_id && $pid){
			$this->update_end($pid);
		}
		return $insert_id;	
		*/
	}
	


    /**
     * 	update group
     * 	@param array $data
     * 	@param array or string $where
     * 	@return int affected count
     */
    public function update_group($data, $where) {
        if (!is_array($data))
            my_jump('输入的参数有误');
			
			
		if($data['g_pid']){
			$row = $this->get_group_row($data['g_pid']);	
			$data['g_nav'] = $row['g_nav'].$data['g_id'].',';
			unset($data['g_id']);
		}
		//my_print($data);
        $result = $this->db->update($this->main_table2, $data, $where);
        return $result;
    }

    /**
     * 	delete group
     * 	@param string $where
     * 	@return int affected count
     */
    public function del_group($id) {

        /*//取得被删除类别的左右值,检测是否有子类,如果有就一起删除
        $row = $this->get_group_row($id);
        $g_left = $row['g_left'];
        $g_right = $row['g_right'];
        //执行删除
		
		$ary =$this->db->getAll("SELECT g_id from ".$this->main_table2." where LOCATE('".$row['g_nav']."',g_nav)=true ");
		foreach($ary as $k=>$v){
			$idlist .= $v['g_id'] ? ','.$v['g_id'] : $v['g_id'];	
		}
		//$this->db->setdebug(1,1);
		$rs = $this->db->delete($this->main_table2, "g_id in (".trim($idlist,',').")");*/
		$rs = $this->db->delete($this->main_table2,"g_id ='".$id."'");
       if($rs){
            return true;
		}else{
            return false;
		}
    }

    /**
     * 	get group row
     * 	@param int $id
     * 	@param array $field or string '*'
     * 	@return array one row data
     */
    public function get_group_row($id, $field='*') {
        $sql = "SELECT " . $field . " FROM " . $this->main_table2 . " WHERE g_id ='" . intval($id) . "' ";
        $data = $this->db->getRow($sql);

        return $data;
    }

    /**
     * 	get power array
     * 	@param array or string $where
     * 	@return array data
     */
    public function get_power_array($where='', $order='power_id DESC', $limit='0', $field='*') {
        if ($where) {
            $where = " WHERE " . $where;
        }
        if (intval($limit)) {
            $limit = " LIMIT " . $limit;
        } else {
            $limit = '';
        }
        $sql = "SELECT " . $field . " FROM " . $this->main_table . $where . " ORDER BY " . $order . $limit;
        $data = $this->db->getAll($sql);
        return $data;
    }

    /**
     * 	get power tree
     * 	@param array or string $where
     * 	@return array data
     */
    public function get_power_tree($where='') {
        $data = $this->get_power_array($where, 'power_controller,power_action');
        if ($data) {
            $pcontroller = '';
            $class_name = '';
            $pkey = 0;
            $new_data = array();
            foreach ($data as $k => $v) {
                if ($pcontroller != $v['power_controller']) {
                    $pcontroller = $v['power_controller'];
                    $pkey++;
                    $v['class'] = 'power' . $pcontroller . $pkey;
                    $new_data[$pkey] = $v;
                }
                $v['class'] = 'power' . $pcontroller . $pkey;
                $new_data[$pkey]['child'][] = $v;
            }
        }
        return $new_data;
    }

    /**
     * 	get power acl
     * 	@param array or string $where
     * 	@return array data
     */
    public function get_power_acl($where='') {
        $data = $this->get_power_array($where, 'power_controller,power_action');

        if ($data) {
            $pcontroller = '';
            $pkey = 0;
            $new_data = array();
            foreach ($data as $k => $v) {
                if ($pcontroller != $v['power_controller']) {
                    $pcontroller = $v['power_controller'];
                    $pkey++;
                    $new_data[$pkey]['controller'] = $pcontroller;
                }
                $new_data[$pkey]['allow'][$v['power_id']] = $v['power_title'];
            }
        }
        return $new_data;
    }

    public function get_group_list() {
        $sql = "SELECT g_id,g_title FROM " . $this->main_table2." WHERE g_level=1";
        $data = $this->db->getAll($sql);
        return change_array($data, 'g_id', 'g_title');
    }

    /**
     * Short description.
     * 1,所有子类,不包含自己;2包含自己的所有子类;3不包含自己所有父类4;包含自己所有父类
     * Detail description
     * @param          none
     * @global          none
     * @since          1.0
     * @access          private
     * @return          void
     * @update          date time
     */
    function get_group_array($id='0', $type='1') {
        if ($id) {
			
			$sql= "SELECT * FROM `" . $this->main_table2 . "` WHERE LOCATE(',".$id.",',g_nav)>0 ";
            /*$row = $this->get_group_row($id, 'g_left,g_right');
            $g_left = $row['g_left'];
            $g_right = $row['g_right'];
            $sql = "SELECT * FROM `" . $this->main_table2 . "` WHERE ";
            switch ($type) {
                case "1":
                    $condition = "`g_left`>$g_left AND `g_right`<$g_right";
                    break;
                case "2":
                    $condition = "`g_left`>=$g_left AND `g_right`<=$g_right";
                    break;
                case "3":
                    $condition = "`g_left`<$g_left AND `g_right`>$g_right";
                    break;
                case "4":
                    $condition = "`g_left`<=$g_left AND `g_right`>=$g_right";
                    break;
                default :
                    $condition = "`g_left`>$g_left AND `g_right`<$g_right";
                    break;
            }*/
        } else {
            $sql = "SELECT * FROM " . $this->main_table2;
        }
        $sql.= " ORDER BY g_root,g_nav ASC";
		
        $list = $this->db->getAll($sql);
        return $list;
    }

	function get_max_gid(){
		$sql = "SELECT max(g_right) FROM ".$this->main_table2 ;
        $id = $this->db->getOne($sql);
		return $id;
	}
	
  function update_act_power($val,$gid_str,$power_id){
	     $sql="update sys_group set  g_act_power=CONCAT_WS(',',g_act_power,'".$val."') where g_id>'1' and `g_id` in (".$gid_str.") and LOCATE(',".$power_id.",',CONCAT(',',g_act_power,','))=false";			
		 $result = $this->db->execute($sql);
		 return $result;
	  }
  function del_act_power($val,$val2){
	  $sql="update sys_group set  g_act_power=REPLACE(CONCAT(',',g_act_power,','), ',".$val.",', ',') where g_id>'1' and `g_id` = '".$val2."' and LOCATE(',".$val.",',CONCAT(',',g_act_power,','))>0";						
	  $result = $this->db->execute($sql);
	  return  $result;
	  
	  }
	  
	function update_view_power($val,$gid_str,$power_id){
	     $sql="update sys_group set  g_view_power=CONCAT_WS(',',g_view_power,'".$val."') where g_id>'1' and `g_id` in (".$gid_str.") and LOCATE(',".$power_id.",',CONCAT(',',g_view_power,','))=false";			
		 $result = $this->db->execute($sql);
		 return $result;
	  }  
	   
}

?>
